﻿package com.xx.xx;

import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yx on 2018/8/16
 */
public class HtmlUtil {

    /**
     * 给文本控件设置富文本数据
     * @param richTxt
     * @param textView
     */
    public static void fromHtml(String richTxt,View textView) {
        Spanned result;
        richTxt = TextUtils.isEmpty(richTxt) ? "" : richTxt;
//        richTxt=UrlUtil.getStringDecode(richTxt);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            result = Html.fromHtml(richTxt, Html.FROM_HTML_MODE_LEGACY);
        } else {
            result = Html.fromHtml(richTxt);
        }
        if(textView instanceof TextView){
            ((TextView)textView).setText(result);
        }else if(textView instanceof EditText){
            ((EditText)textView).setText(result);
        }else{
            throw new IllegalStateException(HtmlUtil.class.getSimpleName() + "必须为文本控件TextView或EditText");
        }
    }

    /**
     * 从html中找出img标签中的图片地址
     *
     * @param html
     * @return
     */
    public static List<String> getImgUrlFromHtml(String html) {
        List<String> results = new ArrayList<>();
        Pattern p = Pattern.compile("<img.*?src.*?=\"(.*?)\"", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(html);
        while (m.find()) {
            results.add(m.group(1));
        }
        return results;
    }
}
